package com.itheima.reggie.controller;

import com.itheima.reggie.config.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
@Api(tags = "员工管理")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     * @param employee
     * @param session
     * @return
     */
    @PostMapping("/login")
    private R login(@RequestBody Employee employee, HttpSession session){
        R<Employee> result = employeeService.login(employee);
        if (result.getCode()==1){
            session.setAttribute("employee",result.getData().getId());
        }
        return result;
    }
    /***
     * 退出登录
     */
    @PostMapping("/logout")
    public R logout(HttpSession session){
        session.invalidate();
        return R.success("退出成功");
    }

    /**
     * 添加员工
     */
    @PostMapping
    public R save(@RequestBody Employee employee,HttpSession session){
        Long empId = (Long)session.getAttribute("employee");
        employee.setUpdateUser(empId);
        employee.setCreateUser(empId);
        employeeService.addEmp(employee);
        return R.success("添加成功");
    }

    /**
     * 分页
     */
    @GetMapping("/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value ="当前页" ),
            @ApiImplicitParam(name = "pageSize",value ="页面大小" )
    })
    public R showPage(@RequestParam(defaultValue = "1")Integer page,
                      @RequestParam(defaultValue = "10")Integer pageSize,
                      String name) {
        Page<Employee> employeePage = employeeService.empByPage(page, pageSize, name);
        return R.success(employeePage);

    }

    /**
     *修改状态员工信息
     */
    @PutMapping
    public R updateEmp(@RequestBody Employee employee,HttpSession session){
//        1.添加修改人的
        Long empId = (Long)session.getAttribute("employee");
        employee.setUpdateUser(empId);
        employeeService.upDate(employee);
        return R.success("修改成功");

    }
    /**
     * 修改员工信息,将数据回显
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable("id") Long id){
        Employee empbyId = employeeService.findById(id);
        return R.success(empbyId);
    }
}
